# -*- coding: utf-8 -*-
import os
import sys
import re
import time
from MyPythonLib.Util import JsonUtil

infos = []
fileTypes = []
projectNames = []


class InfoItem:
    _timestamp = 0
    _type = ''
    _add = 0
    _del = 0
    _fileName = ''
    _hex = ''
    _project = ''
    _branch = ''
    _mon = 0
    _hour = 0

    def __init__(self, tempDict=None):
        if not tempDict:
            return
        self._timestamp = int(tempDict['timestamp'])
        timeArray = time.localtime(self._timestamp)
        self._mon = timeArray.tm_mon
        self._hour = timeArray.tm_hour
        self._add = int(tempDict['add'])
        self._del = int(tempDict['del'])
        self._type = tempDict['type']
        self._fileName = tempDict['fileName']
        self._hex = tempDict['hex']
        self._project = tempDict['project']
        self._branch = tempDict['branch']
        pass


def init():
    global infos, projectNames, fileTypes
    # 1608370961 js 1 1 src/views/home/index.vue 193d6772d0417138b9dd6d39d36b2b5be8f59532 yt_front nanjing 2020-12-19 17:42:41
    dataMatch = re.compile(
        r'(?P<timestamp>\d+) (?P<type>\w+) (?P<add>\d+) (?P<del>\d+) (?P<fileName>.*?) (?P<hex>\w+) (?P<project>\w+) (?P<branch>\w+) (.*)',
        re.I)

    fileFilter = re.compile(
        r'.*?(sqlite3|surface_rc|curl|stb_image|simpleMuxer|qtservice|XsCapturePlugin|IsolationEstimation).*', re.I)
    hexFilter = ["bc79f91745a26beb7e7932fe7d0ca096877e0e39","9f63c76176b101f4f48ae79173554497aac56714"]
    with open("result.record", "r") as f:
        while 1:
            line = f.readline()
            if not line:
                return
            match = dataMatch.match(line)
            if match:
                tempDict = match.groupdict()
                if tempDict['hex'] in hexFilter:
                    continue
                if fileFilter.match(tempDict['fileName']):
                    continue
                item = InfoItem(tempDict)
                if item._type not in fileTypes:
                    fileTypes.append(item._type)
                if item._project not in projectNames:
                    projectNames.append(item._project)

                infos.append(item)
            else:
                print(line)


def filter(startTimeStr='2018-1-1', endTimeStr='2022-1-1', project="*", filetype="*", commithex="*", mon=0, hour=-1,
           data=None):
    global infos
    if not data:
        data = infos
    ret = []
    startTime = int(time.mktime(time.strptime(startTimeStr, "%Y-%m-%d")))
    endTime = int(time.mktime(time.strptime(endTimeStr, "%Y-%m-%d")))
    for item in data:
        if not (item._timestamp >= startTime and item._timestamp <= endTime):
            continue
        if not ("*" == project or item._project == project):
            continue
        if not ("*" == filetype or item._type == filetype):
            continue
        if not ("*" == commithex or item._hex == commithex):
            continue
        if not (0 == mon or item._mon == mon):
            continue
        if not (-1 == hour or item._hour == hour):
            continue
        ret.append(item)
    return ret


def cntTotal(startTimeStr='2018-1-1', endTimeStr='2022-1-1', project="*", filetype="*", commithex="*", mon=0, hour=-1,
             data=None):
    ret = filter(startTimeStr, endTimeStr, project,
                 filetype, commithex, mon, hour, data)
    cnt = 0
    for info in ret:
        cnt += info._add
        if mon == 3 and info._type == "cpp" and info._add > 200:
            print(info._fileName, info._add)
            pass
    return cnt


def getPieLineChart(year):
    totals = [0, 0, 0]
    tempInfos = filter(f"{year}-1-1", f"{year}-12-31", )
    for info in tempInfos:
        totals[0] = totals[0] + info._add
        totals[1] = totals[1] + info._del
    totals[2] = totals[0] - totals[1]
    return [{"value": totals[0], "name": '增加'}, {"value": totals[1], "name": '删除'}, {"value": totals[2], "name": '合计'}]


def getYearLineChart(year):
    ret = []
    datas = {}
    totals = [[0] * 12 for i in range(len(fileTypes))]
    for i in range(1, 13):
        tempInfos = filter(f"{year}-1-1", f"{year}-12-31", mon=i)
        for index, filetype in enumerate(fileTypes):
            totals[index][i -
                          1] = cntTotal(filetype=filetype, mon=i, data=tempInfos)
    print(totals)
    for index, filetype in enumerate(fileTypes):
        ret.append({
            "name": filetype,
            "type": 'line',
            "stack": '总量',
            "areaStyle": {},
            "emphasis": {
                "focus": 'series'
            },
            "data": totals[index]
        })
    return ret


def writeJs(data, name):
    JsonUtil.wirteJsonToFile(data, name)


def getProjectChart(year=2020):
    tempInfos = filter("2020-1-1")
    ret = {}
    pnames = []
    for info in tempInfos:
        pname = info._project
        if pname not in pnames:
            pnames.append(pname)
            ret[pname] = [0, 0, 0]
        ret[pname][0] += info._add
        ret[pname][1] += info._del
        ret[pname][2] += info._add - info._del
    result = []
    print(pnames)
    ret = ret.items()
    pnames = sorted(ret, key=lambda x: x[1][2], reverse=True)
    print(pnames)
    v1 = []
    v2 = []
    v3 = []
    for item in pnames:
        if item[1][2] >=1000:
            print(item[0], ",")
            v1.append(item[1][0])
            v2.append(item[1][1])
            v3.append(item[1][2])

    result.append({
        "name": '新增',
        "type": 'bar',
        "stack": 'all',
        "emphasis": {
            "focus": 'series'
        },
        "data": v1
    })
    result.append({
        "name": '删除',
        "type": 'bar',
        "stack": 'all',
        "emphasis": {
            "focus": 'series'
        },
        "data": v2
    })
    result.append({
        "name": '合计',
        "type": 'bar',
        "stack": 'all',
        "emphasis": {
            "focus": 'series'
        },
        "data": v3
    })
    return result

def getHour(year = 2020):
    tempInfos = filter(f"{year}-1-1",endTimeStr=f"{year+1}-1-1")
    ret = [0 for i in range(24)]
    for i in range(24):
        temp = filter(hour=i,data=tempInfos)
        for info in temp:
            ret[i]+=info._add
    maxAdd = max(ret)
    minAdd = min(ret)
    ret = [(i-minAdd)/(maxAdd -minAdd) for i in ret]
    print(ret)

def getDay(year = 2020):
    tempInfos = filter(f"{year}-1-1", endTimeStr=f"{year }-12-31")
    result={}
    hexs=[]
    for info in tempInfos:
        if info._hex in hexs:
            continue
        hexs.append(info._hex)
        tempTime = time.strftime("%Y-%m-%d", time.localtime(info._timestamp))
        if tempTime not in result:
            result[tempTime] = 0
        result[tempTime] += 1 #info._add
    ret = []
    maxAdd = 0
    minAdd = 0
    for key in result:
        maxAdd = max(maxAdd,result[key])
    for key in result:
        ret.append([key,result[key]/maxAdd * 100])
    return ret

if __name__ == "__main__":
    init()
    d1 = getYearLineChart(2019)
    writeJs(d1, "2019.js")
    d2 = getYearLineChart(2020)
    writeJs(d2, "2020.js")
    d1 = getPieLineChart(2019)
    writeJs(d1, "2019pie.js")
    d2 = getPieLineChart(2020)
    writeJs(d2, "2020pie.js")

    d1 = getProjectChart()
    writeJs(d1, "2020pj.js")
    getHour()
    getHour(2019)
    d1 = getDay(2020)
    writeJs(d1, "2020day.js")